package com.example.moblie.poll;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.moblie.R;

import android.app.Activity;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class comment extends Activity implements OnClickListener {
	String id;
	ArrayList<String[]> cmtdata = new ArrayList<String[]>(); // user, data,
																// content
	int commentIndex = 4;
	Button leaveCmtBtn;
	LinearLayout linearLayout;
	EditText text;
	private ProgressDialog psDialog;
	int countCmt = 0;
	TextView countTxt, titleTxt;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.comment);
		linearLayout = (LinearLayout) findViewById(R.id.Cmtlinear);
		countTxt = (TextView) findViewById(R.id.countTxt);
		titleTxt = (TextView) findViewById(R.id.titleTxt);
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		id = getIntent().getStringExtra("pollid");
		titleTxt.setText(getIntent().getStringExtra("title"));
		psDialog = ProgressDialog.show(this, "", "Loading...");
		cmt_connection cmtcon = new cmt_connection();
		cmtcon.execute(id);
		// getCommentFromServer();
		// showComment();
		leaveCmtBtn = (Button) findViewById(R.id.leaveCmtBtn);
		leaveCmtBtn.setOnClickListener(this);
	}

	public void showComment() {

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		params.setMargins(0, 0, 0, 0);

		int in = commentIndex;
		for (int i = 0; i < cmtdata.size(); i++) {
			String[] data = new String[4];
			data = cmtdata.get(i);
			TextView txt1 = new TextView(this);
			TextView txt2 = new TextView(this);
			TextView txt3 = new TextView(this);

			txt1.setText(data[0] + "                      " + data[1]);
			txt1.setBackgroundColor(0xff708090);
			txt2.setTextColor(0xfff0f8ff);
			txt2.setText(data[2]);
			txt2.setBackgroundColor(0xff072024);
			// txt1.setHint((count + 1) + ".");
			// txt1.setText(options[i]);
			txt1.setLayoutParams(params);
			linearLayout.addView(txt1, in++);
			txt1.setId(in);
			linearLayout.addView(txt2, in++);
			txt2.setId(in);
			linearLayout.addView(txt3, in++);
			// count++;
			
		}
		psDialog.dismiss();
		countTxt.setText(countCmt + " comments");
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.leaveCmtBtn: {
			AlertDialog.Builder editDialog = new AlertDialog.Builder(
					comment.this);
			editDialog.setTitle("Leave comment");
			text = new EditText(this);
			editDialog.setView(text);

			editDialog.setPositiveButton("Submit",
					new DialogInterface.OnClickListener() {
						// do something when the button is clicked
						public void onClick(DialogInterface arg0, int arg1) {
							// textOut.setText(editText.getText().toString());
							submitCommentToServer();
						}
					});
			editDialog.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						// do something when the button is clicked
						public void onClick(DialogInterface arg0, int arg1) {
							// ...

						}
					});
			editDialog.show();
			break;
		}
		}
	}

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			public void run() {
				Toast.makeText(comment.this, toast, Toast.LENGTH_SHORT).show();
			}
		});
	}

	public void submitCommentToServer() {
		psDialog = ProgressDialog.show(this, "", "Uploading...");
		cmt_upload_connection cmtcon = new cmt_upload_connection();
		cmtcon.execute();
	}

	public void refresh() {
		psDialog.dismiss();
		Intent refresh = new Intent(this, comment.class);
		refresh.putExtra("pollid", id);
		refresh.putExtra("title", titleTxt.getText().toString());
		startActivity(refresh);
		this.finish();
	}
/*
	@Override
	public void onBackPressed() {
		// do something on back.
		Intent refresh = new Intent(this, view_poll.class);
		refresh.putExtra("pollid", id);
		startActivity(refresh);
		this.finish();
		return;
	}
*/
	class cmt_connection extends AsyncTask<String, Integer, Integer> {

		@Override
		protected Integer doInBackground(String... params) {
			try {
				String link = "http://myfyp.no-ip.org/cs4295/getCmt.php?pollid="
						+ params[0];
				// execute http request
				HttpClient client = new DefaultHttpClient();
				HttpGet request = new HttpGet(link);
				HttpResponse response = client.execute(request);

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(response.getEntity().getContent()));
				// retrieve http response and save it as a string
				String reply = "";
				String t;
				reply = reader.readLine();
				while ((t = reader.readLine()) != null)
					reply += t;
				reader.close();
				if (!reply.equals("0")) {
					// parse json
					JSONObject json = new JSONObject(reply);
					JSONArray listArray = json.getJSONArray("list");

					for (int i = 0; i < listArray.length(); i++) {
						String[] cl = new String[4];
						JSONObject obj = listArray.getJSONObject(i);
						// cl[i] = new
						// CandidateList(obj.getString("gcId"),obj.getInt("listId"),obj.getInt("candidateNum"),
						// obj.getString("candidateName_zh"),obj.getString("candidateName_en"),obj.getString("partyId"));
						cl[0] = obj.getString("username");
						cl[1] = obj.getString("cdate");
						cl[2] = obj.getString("content");
						cl[3] = obj.getString("userid");
						cmtdata.add(cl);
						countCmt++;
					}
				}
			} catch (Exception e) {
				// showToast(e.getMessage());
				// Toast.makeText(this, e.getMessage(),
				// Toast.LENGTH_LONG).show();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			// showData();
			showComment();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

	}

	class cmt_upload_connection extends AsyncTask<String, Integer, Integer> {

		@Override
		protected Integer doInBackground(String... params) {
			String reply = "", in = "false";
			try {
				HttpPost httpRequest = new HttpPost(
						"http://myfyp.no-ip.org/cs4295/insertCmt.php");
				List<NameValuePair> list1 = new ArrayList<NameValuePair>();
				list1.add(new BasicNameValuePair("userid", "1"));
				list1.add(new BasicNameValuePair("pollid", id));
				list1.add(new BasicNameValuePair("content", text.getText()
						.toString()));
				// list1.add(new BasicNameValuePair("image", img_str));
				httpRequest.setEntity(new UrlEncodedFormEntity(list1,
						HTTP.UTF_8));
				HttpResponse response = new DefaultHttpClient()
						.execute(httpRequest);

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(response.getEntity().getContent()));
				// retrieve http response and save it as a string
				reply = reader.readLine();

				JSONObject json = new JSONObject(reply);

				in = json.getString("insert");
				// showToast(in);
				// Toast.makeText(this, in, Toast.LENGTH_LONG).show();
			} catch (Exception e) {
				// Toast.makeText(this, "error " + reply,
				// Toast.LENGTH_LONG).show();
				// showToast(e.getMessage());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			refresh();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

	}
}